/**
 * Created by huangchao on 14/11/2017.
 */
import React, { Component } from 'react'
import style from './style.less'
import SearchModule from '../../components/SearchModule'
import Layout from '../Wrap'
import {connect} from 'react-redux'
import { Table, Modal, message } from 'antd'
import {Audit} from '../../components/TableBtns'
import ContentWrap from '../Content'
import TableHeader from '../../components/TableHeader'
import {default as ColumnRender} from '../../components/TableColumn'
import F from '../../helper/tool'
import {
  getQueyBest,
  getQeryData,
  selectKey,
  saveUserChecked,
  sortTable,
  getHasSelectitem,
  deleteSelect,
} from '../../actions/search'
import {
  getInitList,
  geiHeiList,
  getNumber,
  userAudit,
} from '../../actions/clueSystem'
const {Wrap} = Layout

@connect((state) => {
  return {
    clueSystem: state.clueSystem,
    search: state.search,
    heiQueryData: state.search.queryData,
    queryBest: state.search.queryBest,
    queryHeiBest: state.search.queryHeiBest,
  }
})
class ClueSystem extends Component {
  constructor(props) {
    super(props)
    this.isBest = true // 判断是否走高级搜索接口
    this.queryCondition = {} // 搜索条件
    this.auditID = [] // 审核的id
  }

  state = {
    heiQueryData: [],
    queryHeiBest: [],
    audit: false,
    modalTwo: false,
    errMsg: '',
    value: 2,
    number: '', // 审核的编号
    columns: [],
  }

  onSelectChange = (key, data) => { // 勾选表格
    console.log(data)
    let number = ''
    data.map((item, index) => {
      item.length === index ? number += item.number : number += item.number + ','
      return {}
    })
    this.props.dispatch(selectKey(key))
    this.auditID = key
    this.setState({number})
  }

  getCheckboxProps = (data) => { // 不能勾选的表格
    const {list} = this.props.clueSystem
    const arr = []
    list.forEach(item => {
      if (item.status === 1) {
        arr.push(item.id)
      }
    })
    return {
      disabled: arr.indexOf(data.id) < 0,
    }
  }

  renderHeaser = () => {
    return (
      <TableHeader
        dataSource={this.props.clueSystem.columns}
        menuSure={this.menuSure}
        upLoadFail={this.upLoadFail}
        submitMoreAudit={this.submitMoreAudit} />
    )
  }

  upLoadFail = (info) => {
    const { page } = this.props.clueSystem
    if (info.file.status !== 'uploading') {
      // console.log(info.file, info.fileList)
    }
    if (info.file.status === 'done') {
      // console.log(info)
      if (info.file.response.code === 0 && info.file.response.msg === '') {
        this.setState({
          errMsg: '上传成功',
          modalTwo: true,
        }, () => {
          this.props.dispatch(getInitList({ // 初始化list
            listType: 1,
            pageNum: page.pageNum,
            pageSize: page.pageSize,
          }))
        })
      } else {
        const errMsg = info.file.response.msg
        this.setState({
          errMsg,
          modalTwo: true,
        })
      }
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name}文件上传失败`)
    }
  }

  singAudit = (record) => { // 单个审核数据
    this.auditID.push(record.id)
    this.setState({
      audit: true,
      number: record.number,
    })
  }

  submitMoreAudit = () => { // 多个审核
    const { selectedRowKeys } = this.props.search
    if (selectedRowKeys.length === 0) {
      return message.info('请选择客户编号', 1)
    }
    this.setState({
      audit: true,
    })
  }

  menuSure = (data) => {
    const columns = data.filter(item => item.checked)
    this.setState({columns})
    console.log(data)
  }

  sortTable = (obj) => { // 排序
    if (obj.items) {
      const list = []
      obj.items.map(item => {
        list.push({
          itemId: item.id,
          sort: item.sort,
        })
        return {}
      })
      this.props.dispatch(sortTable({
        list: JSON.stringify(list),
      }))
    }
  }

  saveUserCheck = (heiQueryData) => { // 保存用户选择的item
    const searchList = []
    heiQueryData.map(item => {
      if (item.checked) {
        searchList.push(item.id)
      }
      return {}
    })
    this.props.dispatch(saveUserChecked({ // 保存已选择的item后重新获取默认的高级搜索项
      searchList,
      listType: 1,
    })).then(() => {
      this.props.dispatch(getHasSelectitem({
        listType: 1,
      }))
    })
  }

  handleQueryBest = (value) => { // 初级查询
    const { page } = this.props.clueSystem
    const ss = F.filterUndefind(value)
    this.isBest = true
    this.queryCondition = ss
    this.props.dispatch(getInitList({
      listType: 1,
      pageNum: page.pageNum,
      pageSize: page.pageSize,
      ...ss,
    }))
  }

  handleHeiQuery = (value) => { // 高级查询
    const { page } = this.props.clueSystem
    const ss = F.filterUndefind(value)
    this.isBest = false
    this.queryCondition = JSON.stringify(ss)
    this.props.dispatch(geiHeiList({
      listType: 1,
      pageNum: page.pageNum,
      pageSize: page.pageSize,
      search: JSON.stringify(ss),
      // ...ss,
    }))
  }

  onShowSizeChange = (pageNum, pageSize) => { // 点击每页显示个数
    if (this.isBest) { // 走基本搜索接口
      this.props.dispatch(getInitList({
        listType: 1,
        pageNum: pageNum,
        pageSize: pageSize,
        ...this.queryCondition,
      }))
    } else { //  走高级搜索接口
      this.props.dispatch(geiHeiList({
        listType: 1,
        pageNum: pageNum,
        pageSize: pageSize,
        search: this.queryCondition,
      }))
    }
  }

  pageChange = (pageNum, pageSize) => { // 点击页数
    if (this.isBest) { // 走基本搜索接口
      this.props.dispatch(getInitList({
        listType: 1,
        pageNum: pageNum,
        pageSize: pageSize,
        ...this.queryCondition,
      }))
    } else { //  走高级搜索接口
      console.log(this.queryCondition)
      this.props.dispatch(geiHeiList({
        listType: 1,
        pageNum: pageNum,
        pageSize: pageSize,
        search: this.queryCondition,
      }))
    }
  }

  selectRadio = (e) => {
    this.setState({
      value: e.target.value,
    })
  }

  handleCancel = () => {
    this.setState({
      visible: false,
      modalTwo: false,
    })
  }

  handleChange = (pagination, filters, sorter) => {
    console.log('Various parameters', pagination, filters, sorter)
  }

  auditCancle = () => {
    this.auditID = []
    this.setState({audit: false})
  }

  auditOk = (value) => { // 审核
    console.log(value)
    this.props.dispatch(userAudit({...value})).then(data => {
      if (data) {
        message.success(data.msg)
        this.auditCancle()
      }
    })
  }

  componentWillMount() {
    const columns = this.props.clueSystem.columns.filter(item => item.checked)
    this.setState({columns})
  }

  componentDidMount() {
    const { page } = this.props.clueSystem
    this.props.dispatch(getQueyBest({ // 初级查询 数据
      defaut: 1,
    }))
    this.props.dispatch(getHasSelectitem({ // 高级搜索 默认item
      listType: 1,
    }))
    this.props.dispatch(getQeryData({ // 高级搜索 所有数据
      listType: 1,
    }))
    this.props.dispatch(getInitList({ // 初始化list
      listType: 1,
      pageNum: page.pageNum,
      pageSize: page.pageSize,
    }))
    this.props.dispatch(getNumber()) // 获取个数
  }

  componentWillReceiveProps(props) {
    this.setState({
      heiQueryData: props.heiQueryData,
      queryHeiBest: props.queryHeiBest,
    })
  }

  componentWillUnmount() {
    this.props.dispatch(deleteSelect)
  }

  render() {
    const { queryBest } = this.props
    const { queryHeiBest, heiQueryData, columns } = this.state
    const { page, list } = this.props.clueSystem
    const { selectedRowKeys } = this.props.search
    // console.log(list)

    columns.forEach((item, index) => {
      if(item.dataIndex === 'name'){
        columns[index].sorter = (a, b) => a.name.length - b.name.length
        columns[index].render = (text, record) => {
          const url = `/clue/${record.key}?id=${record.key}&customerCategory=${record.type}&action=2&status=${record.status}&topName=线索管理`
          return <ColumnRender.NewTable text={text} url={url} />
        }
      }
      if(item.dataIndex === 'action'){
        columns[index].render = (text, record) => {
          return <ColumnRender.AuditBtn singAudit={this.singAudit} record={record} />
        }
      }
    })

    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
      getCheckboxProps: this.getCheckboxProps,
    }

    let pagination = {
      onChange: this.pageChange,
      onShowSizeChange: this.onShowSizeChange,
      total: page.total,
      defaultCurrent: page.pageNum,
      pageSize: page.pageSize,
      showSizeChanger: true,
      showQuickJumper: true,
    }

    // console.log(list)
    // console.log(heiQueryData)
    return (
      <Layout>
        <Wrap>
          <div className={style.ClueSystemWrap}>
            <SearchModule
              showHeiBtn
              handleQueryBest={this.handleQueryBest}
              handleHeiQuery={this.handleHeiQuery}
              saveUserCheck={this.saveUserCheck}
              sortTable={this.sortTable}
              queryBest={queryBest}
              queryHeiBest={queryHeiBest}
              heiQueryData={heiQueryData}
            />
            <ContentWrap>
              <Table
                onChange={this.handleChange}
                title={this.renderHeaser}
                className={style.table}
                rowSelection={rowSelection}
                columns={columns}
                dataSource={list}
                pagination={pagination}
              />
            </ContentWrap>
          </div>
          <Audit
            title="线索审核"
            disabled={false}
            visible={this.state.audit}
            cancle={this.auditCancle}
            ids={this.auditID}
            ok={this.auditOk}
          />
          <Modal
            title="上传文件"
            visible={this.state.modalTwo}
            onOk={this.handleCancel}
            onCancel={this.handleCancel}
            className={style.Modal}
          >
            <p dangerouslySetInnerHTML={{__html: this.state.errMsg}} />
          </Modal>
        </Wrap>
      </Layout>
    )
  }
}

export default ClueSystem
